// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

#include <PyColorControlPoint.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <Py2and3Support.h>

// ****************************************************************************
// Module: PyColorControlPoint
//
// Purpose:
//   This class contains an RGBA color with a position value.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

//
// This struct contains the Python type information and a ColorControlPoint.
//
struct ColorControlPointObject
{
    PyObject_HEAD
    ColorControlPoint *data;
    bool        owns;
    PyObject   *parent;
};

//
// Internal prototypes
//
static PyObject *NewColorControlPoint(int);
std::string
PyColorControlPoint_ToString(const ColorControlPoint *atts, const char *prefix, const bool forLogging)
{
    std::string str;
    char tmpStr[1000];

    {   const unsigned char *colors = atts->GetColors();
        snprintf(tmpStr, 1000, "%scolors = (", prefix);
        str += tmpStr;
        for(int i = 0; i < 4; ++i)
        {
            snprintf(tmpStr, 1000, "%d", int(colors[i]));
            str += tmpStr;
            if(i < 3)
            {
                snprintf(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        snprintf(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    snprintf(tmpStr, 1000, "%sposition = %g\n", prefix, atts->GetPosition());
    str += tmpStr;
    return str;
}

static PyObject *
ColorControlPoint_Notify(PyObject *self, PyObject *args)
{
    ColorControlPointObject *obj = (ColorControlPointObject *)self;
    obj->data->Notify();
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorControlPoint_SetColors(PyObject *self, PyObject *args)
{
    ColorControlPointObject *obj = (ColorControlPointObject *)self;

    typedef unsigned char uchar;
    PyObject *packaged_args = 0;
    uchar *vals = obj->data->GetColors();

    if (!PySequence_Check(args) || PyUnicode_Check(args))
        return PyErr_Format(PyExc_TypeError, "Expecting a sequence of numeric args");

    // break open args seq. if we think it matches this API's needs
    if (PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PySequence_Check(packaged_args) && !PyUnicode_Check(packaged_args) &&
            PySequence_Size(packaged_args) == 4)
            args = packaged_args;
    }

    if (PySequence_Size(args) != 4)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "Expecting 4 numeric args");
    }

    for (Py_ssize_t i = 0; i < PySequence_Size(args); i++)
    {
        PyObject *item = PySequence_GetItem(args, i);

        if (!PyNumber_Check(item))
        {
            Py_DECREF(item);
            Py_XDECREF(packaged_args);
            return PyErr_Format(PyExc_TypeError, "arg %d is not a number type", (int) i);
        }

        long val = PyLong_AsLong(item);
        uchar cval = uchar(val);

        if (val == -1 && PyErr_Occurred())
        {
            Py_XDECREF(packaged_args);
            Py_DECREF(item);
            PyErr_Clear();
            return PyErr_Format(PyExc_TypeError, "arg %d not interpretable as C++ uchar", (int) i);
        }
        if (fabs(double(val))>1.5E-7 && fabs((double(long(cval))-double(val))/double(val))>1.5E-7)
        {
            Py_XDECREF(packaged_args);
            Py_DECREF(item);
            return PyErr_Format(PyExc_ValueError, "arg %d not interpretable as C++ uchar", (int) i);
        }
        Py_DECREF(item);

        vals[i] = cval;
    }

    Py_XDECREF(packaged_args);

    // Mark the colors in the object as modified.
    obj->data->SelectColors();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorControlPoint_GetColors(PyObject *self, PyObject *args)
{
    ColorControlPointObject *obj = (ColorControlPointObject *)self;
    // Allocate a tuple the with enough entries to hold the colors.
    PyObject *retval = PyTuple_New(4);
    const unsigned char *colors = obj->data->GetColors();
    for(int i = 0; i < 4; ++i)
        PyTuple_SET_ITEM(retval, i, PyInt_FromLong(long(colors[i])));
    return retval;
}

/*static*/ PyObject *
ColorControlPoint_SetPosition(PyObject *self, PyObject *args)
{
    ColorControlPointObject *obj = (ColorControlPointObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged into a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyNumber_Check(packaged_args))
            args = packaged_args;
    }

    if (PySequence_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "expecting a single number arg");
    }

    if (!PyNumber_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a number type");
    }

    double val = PyFloat_AsDouble(args);
    float cval = float(val);

    if (val == -1 && PyErr_Occurred())
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ float");
    }
    if (fabs(double(val))>1.5E-7 && fabs((double(double(cval))-double(val))/double(val))>1.5E-7)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_ValueError, "arg not interpretable as C++ float");
    }

    Py_XDECREF(packaged_args);

    // Set the position in the object.
    obj->data->SetPosition(cval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorControlPoint_GetPosition(PyObject *self, PyObject *args)
{
    ColorControlPointObject *obj = (ColorControlPointObject *)self;
    PyObject *retval = PyFloat_FromDouble(double(obj->data->GetPosition()));
    return retval;
}



PyMethodDef PyColorControlPoint_methods[COLORCONTROLPOINT_NMETH] = {
    {"Notify", ColorControlPoint_Notify, METH_VARARGS},
    {"SetColors", ColorControlPoint_SetColors, METH_VARARGS},
    {"GetColors", ColorControlPoint_GetColors, METH_VARARGS},
    {"SetPosition", ColorControlPoint_SetPosition, METH_VARARGS},
    {"GetPosition", ColorControlPoint_GetPosition, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

static void
ColorControlPoint_dealloc(PyObject *v)
{
   ColorControlPointObject *obj = (ColorControlPointObject *)v;
   if(obj->parent != 0)
       Py_DECREF(obj->parent);
   if(obj->owns)
       delete obj->data;
}

static PyObject *ColorControlPoint_richcompare(PyObject *self, PyObject *other, int op);
PyObject *
PyColorControlPoint_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "colors") == 0)
        return ColorControlPoint_GetColors(self, NULL);
    if(strcmp(name, "position") == 0)
        return ColorControlPoint_GetPosition(self, NULL);


    // Add a __dict__ answer so that dir() works
    if (!strcmp(name, "__dict__"))
    {
        PyObject *result = PyDict_New();
        for (int i = 0; PyColorControlPoint_methods[i].ml_meth; i++)
            PyDict_SetItem(result,
                PyString_FromString(PyColorControlPoint_methods[i].ml_name),
                PyString_FromString(PyColorControlPoint_methods[i].ml_name));
        return result;
    }

    return Py_FindMethod(PyColorControlPoint_methods, self, name);
}

int
PyColorControlPoint_setattr(PyObject *self, char *name, PyObject *args)
{
    PyObject NULL_PY_OBJ;
    PyObject *obj = &NULL_PY_OBJ;

    if(strcmp(name, "colors") == 0)
        obj = ColorControlPoint_SetColors(self, args);
    else if(strcmp(name, "position") == 0)
        obj = ColorControlPoint_SetPosition(self, args);

    if (obj != NULL && obj != &NULL_PY_OBJ)
        Py_DECREF(obj);

    if (obj == &NULL_PY_OBJ)
    {
        obj = NULL;
        PyErr_Format(PyExc_NameError, "name '%s' is not defined", name);
    }
    else if (obj == NULL && !PyErr_Occurred())
        PyErr_Format(PyExc_RuntimeError, "unknown problem with '%s'", name);

    return (obj != NULL) ? 0 : -1;
}

static int
ColorControlPoint_print(PyObject *v, FILE *fp, int flags)
{
    ColorControlPointObject *obj = (ColorControlPointObject *)v;
    fprintf(fp, "%s", PyColorControlPoint_ToString(obj->data, "",false).c_str());
    return 0;
}

PyObject *
ColorControlPoint_str(PyObject *v)
{
    ColorControlPointObject *obj = (ColorControlPointObject *)v;
    return PyString_FromString(PyColorControlPoint_ToString(obj->data,"", false).c_str());
}

//
// The doc string for the class.
//
#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
static const char *ColorControlPoint_Purpose = "This class contains an RGBA color with a position value.";
#else
static char *ColorControlPoint_Purpose = "This class contains an RGBA color with a position value.";
#endif

//
// Python Type Struct Def Macro from Py2and3Support.h
//
//         VISIT_PY_TYPE_OBJ( VPY_TYPE,
//                            VPY_NAME,
//                            VPY_OBJECT,
//                            VPY_DEALLOC,
//                            VPY_PRINT,
//                            VPY_GETATTR,
//                            VPY_SETATTR,
//                            VPY_STR,
//                            VPY_PURPOSE,
//                            VPY_RICHCOMP,
//                            VPY_AS_NUMBER)

//
// The type description structure
//

VISIT_PY_TYPE_OBJ(ColorControlPointType,         \
                  "ColorControlPoint",           \
                  ColorControlPointObject,       \
                  ColorControlPoint_dealloc,     \
                  ColorControlPoint_print,       \
                  PyColorControlPoint_getattr,   \
                  PyColorControlPoint_setattr,   \
                  ColorControlPoint_str,         \
                  ColorControlPoint_Purpose,     \
                  ColorControlPoint_richcompare, \
                  0); /* as_number*/

//
// Helper function for comparing.
//
static PyObject *
ColorControlPoint_richcompare(PyObject *self, PyObject *other, int op)
{
    // only compare against the same type 
    if ( Py_TYPE(self) != &ColorControlPointType
         || Py_TYPE(other) != &ColorControlPointType)
    {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    PyObject *res = NULL;
    ColorControlPoint *a = ((ColorControlPointObject *)self)->data;
    ColorControlPoint *b = ((ColorControlPointObject *)other)->data;

    switch (op)
    {
       case Py_EQ:
           res = (*a == *b) ? Py_True : Py_False;
           break;
       case Py_NE:
           res = (*a != *b) ? Py_True : Py_False;
           break;
       default:
           res = Py_NotImplemented;
           break;
    }

    Py_INCREF(res);
    return res;
}

//
// Helper functions for object allocation.
//

static ColorControlPoint *defaultAtts = 0;
static ColorControlPoint *currentAtts = 0;

static PyObject *
NewColorControlPoint(int useCurrent)
{
    ColorControlPointObject *newObject;
    newObject = PyObject_NEW(ColorControlPointObject, &ColorControlPointType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new ColorControlPoint(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new ColorControlPoint(*defaultAtts);
    else
        newObject->data = new ColorControlPoint;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapColorControlPoint(const ColorControlPoint *attr)
{
    ColorControlPointObject *newObject;
    newObject = PyObject_NEW(ColorControlPointObject, &ColorControlPointType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (ColorControlPoint *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

///////////////////////////////////////////////////////////////////////////////
//
// Interface that is exposed to the VisIt module.
//
///////////////////////////////////////////////////////////////////////////////

PyObject *
ColorControlPoint_new(PyObject *self, PyObject *args)
{
    int useCurrent = 0;
    if (!PyArg_ParseTuple(args, "i", &useCurrent))
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        else
            PyErr_Clear();
    }

    return (PyObject *)NewColorControlPoint(useCurrent);
}

//
// Plugin method table. These methods are added to the visitmodule's methods.
//
static PyMethodDef ColorControlPointMethods[] = {
    {"ColorControlPoint", ColorControlPoint_new, METH_VARARGS},
    {NULL,      NULL}        /* Sentinel */
};

static Observer *ColorControlPointObserver = 0;

std::string
PyColorControlPoint_GetLogString()
{
    std::string s("ColorControlPoint = ColorControlPoint()\n");
    if(currentAtts != 0)
        s += PyColorControlPoint_ToString(currentAtts, "ColorControlPoint.", true);
    return s;
}

static void
PyColorControlPoint_CallLogRoutine(Subject *subj, void *data)
{
    typedef void (*logCallback)(const std::string &);
    logCallback cb = (logCallback)data;

    if(cb != 0)
    {
        std::string s("ColorControlPoint = ColorControlPoint()\n");
        s += PyColorControlPoint_ToString(currentAtts, "ColorControlPoint.", true);
        cb(s);
    }
}

void
PyColorControlPoint_StartUp(ColorControlPoint *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyColorControlPoint_SetDefaults(subj);

    //
    // Create the observer that will be notified when the attributes change.
    //
    if(ColorControlPointObserver == 0)
    {
        ColorControlPointObserver = new ObserverToCallback(subj,
            PyColorControlPoint_CallLogRoutine, (void *)data);
    }

}

void
PyColorControlPoint_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete ColorControlPointObserver;
    ColorControlPointObserver = 0;
}

PyMethodDef *
PyColorControlPoint_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return ColorControlPointMethods;
}

bool
PyColorControlPoint_Check(PyObject *obj)
{
    return (obj->ob_type == &ColorControlPointType);
}

ColorControlPoint *
PyColorControlPoint_FromPyObject(PyObject *obj)
{
    ColorControlPointObject *obj2 = (ColorControlPointObject *)obj;
    return obj2->data;
}

PyObject *
PyColorControlPoint_New()
{
    return NewColorControlPoint(0);
}

PyObject *
PyColorControlPoint_Wrap(const ColorControlPoint *attr)
{
    return WrapColorControlPoint(attr);
}

void
PyColorControlPoint_SetParent(PyObject *obj, PyObject *parent)
{
    ColorControlPointObject *obj2 = (ColorControlPointObject *)obj;
    obj2->parent = parent;
}

void
PyColorControlPoint_SetDefaults(const ColorControlPoint *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new ColorControlPoint(*atts);
}

